package com.example;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShiroTest {
    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

    public static void main(String[] args) {

        //1.初始化获取securityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //2.Subject对象currentUser
        Subject currentUser = SecurityUtils.getSubject();
        //3.创建token对象 web应用用户名从页面传递
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        //4.完成登陆
        try {
            currentUser.login(token);
            System.out.println("登陆成功");
            /*
                用户[users]后配上角色，角色[roles]配上权限。
             */
            //5.判断角色
            boolean hasRole1 = currentUser.hasRole("goodguy");//admin:false lonestarr拥有权限goodguy, schwartz
            System.out.println("是否拥有此角色"+hasRole1);
            //6.判断权限
            boolean permitted = currentUser.isPermitted("user:select");
            System.out.println("是否拥有此权限"+permitted);
            //也可以用 checkPermission方法，但没有返回值，没权限就抛AuthenticationError异常。
            currentUser.checkPermission("user:select");

        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                    "Please contact your administrator to unlock it.");
        }
        catch (AuthenticationException ae) {
        }
    }
}